<?php

class CheckLockedUpdatesTask extends sfBaseTask
{
    protected function configure()
    {
        $this->addOptions(array(
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environement', 'prod'),
        ));
        
        $this->namespace = 'updates';
        $this->name = 'check-locked';
        $this->briefDescription = 'Check to see if there\'s any updates that have got into a locked state';
        $this->detailedDescription = '';
    }
    
    protected function execute($arguments = array(), $options = array())
    {
        // Required to allow database queries
        $databaseManager = new sfDatabaseManager($this->configuration);
        
        $limitDate = date('Y-m-d H:i:s', (time() - Config::$lockedUpdatesCheckFrequency));
        
        $lockedUpdates = Doctrine_Core::getTable('SourceRefreshRun')
                ->createQuery('srr')
                ->where('srr.start_date IS NOT NULL')
                ->andWhere('srr.end_date IS NULL')
                ->andWhere('((srr.last_activity_date <= "' . $limitDate . '") OR (srr.last_activity_date IS NULL AND srr.start_date <= "' . $limitDate . '"))')
                ->execute();
        if ($lockedUpdates->count() > 0) {
            
            foreach ($lockedUpdates as $lockedUpdate) {
                Doctrine_Core::getTable('Source')
                    ->createQuery('s')
                    ->where('s.id = ?', $lockedUpdate->getSourceId())
                    ->execute();
                    
                $source = Doctrine_Core::getTable('Source')->find($lockedUpdate->getSourceId());
                if ($source) {
                    $source->setAllowUpdates(0);
                    $source->save();
                    
                    EmailHelper::send("cameron.ross@gmail.com", "Locked Fydal updates", "The source \"" . $source->getName() . "\" has had its updates disabled as a result of run #" . $lockedUpdate->getId() . ", which started at " . $lockedUpdate->getStartDate() . " having issues.");
                    
                    $lockedUpdate->setEndDate(date("Y-m-d H:i:s"));
                    $lockedUpdate->setCompletedSuccessfully(0);
                    $lockedUpdate->save();
                }
            }
        }
        
        echo "Done." . PHP_EOL;
    }
}